Plotting with Matplotlib

Preparations


In [1]:
import numpy as np
import scipy as sp
import sympy

# the convienient Matplotib plotting interface pyplot (the tidy/right way)
# use this for building scripts
import matplotlib.pyplot as plt

# for using the matplotlib API directly (the hard and verbose way)
# use this when building applications, and/or backends
import matplotlib as mpl

Scaling: getting font sizes right for publications


In [2]:
# some sample data
x = np.arange(0,10,0.1)

In [3]:
page_width_cm = 13
dpi = 200
inch = 2.54 # inch in cm

plt.rc('font', family='serif')
plt.rc('xtick', labelsize=12) # tick labels
plt.rc('ytick', labelsize=20) # tick labels
plt.rc('axes', labelsize=20)  # axes labels
# If you don’t need LaTeX, don’t use it. It is slower to plot, and text
# looks just fine without. If you need it, e.g. for symbols, then use it.
plt.rc('text', usetex=True)

In [4]:
# chose the backend: 'gtk', 'inline', 'osx', 'qt', 'qt4', 'tk', 'wx'
%matplotlib qt
# create a figure instance, note that figure size is given in inches!
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(8,6))
# set the big title (note aligment relative to figure)
fig.suptitle("suptitle 16, figure alignment", fontsize=16)
# add axes to plot manually
# left, bottom, width, height (range 0 to 1)
ax = fig.add_axes([0.1, 0.1, 0.5, 0.8])
# actual plotting
ax.plot(x, x**2, label="label 12")
# set axes title (note aligment relative to axes)
ax.set_title("title 14, axes alignment", fontsize=14)
# axes labels
ax.set_xlabel('xlabel 12')
ax.set_ylabel(r'$y_{\alpha}$ 12', fontsize=8)
# legend
ax.legend(fontsize=12, loc="best")
fig.savefig('figure-%03i.png' % dpi, dpi=dpi)
fig.savefig('figure.svg')
fig.savefig('figure.eps')

# figure scope
y_ = 0.7
ax.annotate('',  xy=(0.0, y_), xycoords='figure fraction',
             xytext=(0.1, y_), textcoords='figure fraction',
             arrowprops=dict(arrowstyle="<->"))
ax.annotate('',  xy=(0.1, y_), xycoords='figure fraction',
             xytext=(0.6, y_), textcoords='figure fraction',
             arrowprops=dict(arrowstyle="<->"))
ax.annotate('',  xy=(0.6, y_), xycoords='figure fraction',
             xytext=(1.0, y_), textcoords='figure fraction',
             arrowprops=dict(arrowstyle="<->"))

x_ = 0.15
ax.annotate('',  xy=(x_, 0), xycoords='figure fraction',
             xytext=(x_, 0.1), textcoords='figure fraction',
             arrowprops=dict(arrowstyle="<->"))
ax.annotate('',  xy=(x_, 0.1), xycoords='figure fraction',
             xytext=(x_, 0.9), textcoords='figure fraction',
             arrowprops=dict(arrowstyle="<->"))
ax.annotate('',  xy=(x_, 0.9), xycoords='figure fraction',
             xytext=(x_, 1.0), textcoords='figure fraction',
             arrowprops=dict(arrowstyle="<->"))


Out[4]:
<matplotlib.text.Annotation at 0x6a57e90>

In [8]:
stext = u'$\\sigma = \\frac{33 \\cdot 10^3 \\Omega}{5 \\epsilon^5}$'
# bbox is a dictionary of matplotlib.patches.Rectangle properties:
# http://matplotlib.org/api/artist_api.html#matplotlib.patches.Rectangle
bbox = dict(boxstyle="round", alpha=0.5, edgecolor=(1., 0.5, 0.5),
            facecolor=(1., 0.8, 0.8),)
ax.text(6, 40, stext, fontsize=24, verticalalignment='bottom',
         horizontalalignment='center', bbox=bbox)
# we have to update the figure
ax.plot(x, x**2, 'ks', label="label 12", alpha=0.3)
fig.canvas.draw()

In [6]:
# what is the current backend?
%matplotlib
fig = plt.figure(1, figsize=(8,6))
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
ax.plot(x, x**2, label="label 12")


Using matplotlib backend: Qt4Agg
Out[6]:
[<matplotlib.lines.Line2D at 0x5588450>]

In [7]:
# switch to inline plotting
%matplotlib inline
fig = plt.figure(1, figsize=(8,6))
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
ax.plot(x, x**2, label="label 12")


Out[7]:
[<matplotlib.lines.Line2D at 0x5662ed0>]

In [8]:
%matplotlib qt
fig = plt.figure(1, figsize=(8,6))
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
ax.plot(x, x**2, label="label 12")


Out[8]:
[<matplotlib.lines.Line2D at 0x5589710>]

In [9]:
%matplotlib?

In [10]:
for i in range(5):
    plt.figure(i)
    plt.plot(x, i*x**2)

In [11]:
def serialplots():
    for i in range(5):
        plt.figure(i)
        plt.plot(x, i*x**2)
        plt.show()

def serialplots2():
    for i in range(5):
        plt.figure(i)
        plt.plot(x, i*x**2)
    plt.show()

def serialplots3():
    for i in range(5):
        figure(i)
        plot(x, i*x**2)
        show()

def serialplots4():
    for i in range(5):
        figure(i)
        plot(x, i*x**2)
    show()

In [12]:
%matplotlib qt
serialplots4()